package org.amos.msg.platform.sms;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.utils.JsonUtils;
import org.amos.msg.model.SmsContentModel;
import org.amos.msg.params.PushMsgParam;
import org.amos.msg.platform.AbstractMsgPlatform;

@Slf4j
public class AliyunMsgPlatform extends AbstractMsgPlatform<AliyunMsgConfig> {

    private IAcsClient client;
    private static final String REGION_ID = "cn-hangzhou";
    public static final String SUCCESS_CODE = "OK";

    public AliyunMsgPlatform(String id, AliyunMsgConfig config) {
        super(id, config);
    }

    @Override
    protected void initClient() {
        IClientProfile profile = DefaultProfile.getProfile(REGION_ID, config.getAccessKey(), config.getSecretKey());
        client = new DefaultAcsClient(profile);
    }

    @Override
    public Boolean push(PushMsgParam param) {
        try {
            SmsContentModel contentModel = (SmsContentModel) param.getContentModel();
            // 构建参数
            SendSmsRequest request = new SendSmsRequest();
            request.setPhoneNumbers(String.join(",", param.getReceiver()));
            request.setSignName(config.getSignature());
            request.setTemplateCode(config.getTemplateCode());
            request.setTemplateParam(contentModel.getContent());
            request.setOutId(param.getBusinessId());

            SendSmsResponse response = client.getAcsResponse(request);
            String code = response.getCode();
            if (SUCCESS_CODE.equals(code)) {
                return Boolean.TRUE;
            } else {
                log.error("[阿里云短信发送]，异常信息：{}", JsonUtils.objectToJson(response));
            }
        } catch (ClientException e) {
            log.error("[阿里云短信发送异常]，异常信息：{}", Throwables.getStackTraceAsString(e));
        }
        return Boolean.FALSE;
    }
}
